<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\common\model;

use app\common\enum\order\DeliveryStatus as DeliveryStatusEnum;
use app\common\enum\order\DeliveryType as DeliveryTypeEnum;
use app\common\enum\order\OrderStatus as OrderStatusEnum;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\ReceiptStatus as ReceiptStatusEnum;
use app\common\enum\order\ServiceStatus as ServiceStatusEnum;
use app\common\library\helper;
use app\common\model\store\shop\Order as ShopOrder;
use app\common\service\Order as OrderService;
use app\common\service\order\Complete as OrderCompleteService;
use app\common\service\order\Shipping as ShippingService;
use app\common\service\order\source\Factory as OrderSourceFactory;
use app\store\service\wxapp\Message as MessageService;
use cores\BaseModel;
use think\facade\Db;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * 订单模型
 * Class Order
 * @package app\common\model
 */
class Order extends BaseModel
{
    // 定义表名
    protected $name = 'order';

    // 定义表名(外部引用)
    public static string $tableName = 'order';

    // 定义主键
    protected $pk = 'order_id';

    // 定义别名
    protected string $alias = 'order';

    /**
     * 追加字段
     * @var array
     */
    protected $append = [
        'state_text',  // 售后单状态文字描述
        'status_text', //服务订单状态
        'service_time',
        'service_text',
        'min_date',
        'hour_type_text',
        'driver_status',
        'runner_status',
        'order_type_text',
    ];
    public function getOrderTypeTextAttr($value, $data): string
    {
        $text = '';
        switch ($data['order_type']) {
            case 10:
                $text = '住院/居家陪护';
                break;
            case 20:
                $text = '代泊车';
                break;
            case 30:
                $text = '跑腿';
                break;
            case 40:
                $text = '陪诊陪检';
                break;

            default:
                // code...
                break;
        }

        return $text;
    }
    public function getServiceTextAttr($value, $data): string
    {
        $text = '';
        if ($data['service_type'] == 10) {
            $text = '代泊车';
        }
        if ($data['service_type'] == 20) {
            $text = '上门接送';
        }

        return $text;
    }
    public function getHourTypeTextAttr($value, $data): string
    {

        return $data['hour_type'] == 20 ? '24小时制' : '12小时制';
    }
    public function getMinDateAttr($value, $data): string
    {
        $time = strtotime($data['end_date']) + 86400;

        return Date('Y-m-d', $time);
    }

    /**
     * 订单商品列表
     * @return HasMany
     */
    public function goods(): HasMany
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\OrderGoods")->withoutField('content');
    }

    public function images(): HasMany
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\jia\\OrderImage");
    }
    //派单主管，

    public function paidaner(): HasOne
    {

        return $this->hasOne("app\\common\\model\\store\\shop\\Manage", 'clerk_id', 'paidaner_id');
    }

    public function manage(): HasOne
    {

        return $this->hasOne("app\\common\\model\\store\\shop\\Manage", 'user_id', 'manage_id');
    }
   public function rooms(): HasOne
    {

        return $this->hasOne("app\\common\\model\\jia\\Room", 'room_id', 'room_id');
    }

    public function driver(): HasOne
    {
        $module = self::getCalledModule();
        return $this->HasOne("app\\{$module}\\model\\store\\shop\\Driver", 'driver_id', 'driver_id');
    }
    public function runner(): HasOne
    {
        $module = self::getCalledModule();
        return $this->HasOne("app\\{$module}\\model\\store\\shop\\Runner", 'runner_id', 'runner_id');
    }

    /**
     * 关联订单发货单
     * @return hasMany
     */
    public function delivery(): HasMany
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\order\\Delivery");
    }
    public function category(): HasOne
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\Category", 'category_id', 'category_id')
            ->bind(['category_name' => 'name']);
    }

    /**
     * 关联订单收货地址表
     * @return HasOne
     */
    public function address(): HasOne
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\OrderAddress");
    }

    /**
     * 关联订单收货地址表
     * @return HasOne
     */
    public function extract(): HasOne
    {
        $module = self::getCalledModule();
        return $this->hasOne("app\\{$module}\\model\\OrderExtract");
    }

    /**
     * 关联自提门店表
     * @return BelongsTo
     */
    public function extractShop(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\Shop", 'extract_shop_id');
    }
    public function pdf(): HasOne
    {
        $module = self::getCalledModule();
        return $this->HasOne("app\\{$module}\\model\\jia\\Contract", 'order_id', 'order_id');
    }
    public function build(): HasOne
    {
        $module = self::getCalledModule();
        return $this->HasOne("app\\{$module}\\model\\jia\\Build", 'build_id', 'build_id');
    }
    public function changeLog(): HasMany
    {
        $module = self::getCalledModule();
        return $this->HasMany("app\\{$module}\\model\\jia\\BuildChange", 'order_id', 'order_id');
    }
    /**
     * 关联门店店员表
     * @return BelongsTo
     */
    public function extractClerk(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\shop\\Clerk", 'extract_clerk_id');
    }
  public function group(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\shop\\ClerkGroup", 'group_id','id');
    }

    /**
     * 关联用户表
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User");
    }

    public function log()
    {
        $module = self::getCalledModule();
        return $this->hasMany("app\\{$module}\\model\\OrderPayLog");
    }
    /**
     * 关联物流公司表 (仅用于兼容旧物流数据)
     * @return BelongsTo
     */
    public function express(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\Express");
    }

    /**
     * 关联模型：第三方交易记录
     * @return BelongsTo
     */
    public function trade(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\PaymentTrade", 'trade_id', 'trade_id');
    }
    /**
     * 泊车状态
     * @param $value
     * @param $data
     * @return string
     */
    public function getDriverStatusAttr($value, $data): string
    {
        $value = '';
        // 订单状态
        if ($data['order_status'] != OrderStatusEnum::NORMAL) {
            return OrderStatusEnum::data()[$data['order_status']]['name'];
        }
        // 付款状态
        if ($data['pay_status'] == PayStatusEnum::PENDING) {
            return '待支付';
        }
        // 发货状态
        if ($data['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
            $enum = [DeliveryStatusEnum::NOT_DELIVERED => '待接车', DeliveryStatusEnum::PART_DELIVERED => '部分发货'];
            return $enum[$data['delivery_status']];
        }
        // 待还车
        if ($data['receipt_status'] == ReceiptStatusEnum::NOT_RECEIVED) {
            return '待还车';
        }
        return $value;
    }
    /**
     * 陪诊状态
     * @param $value
     * @param $data
     * @return string
     */
    public function getRunnerStatusAttr($value, $data): string
    {
        $value = '';
        // 订单状态
        if ($data['order_status'] != OrderStatusEnum::NORMAL) {
            return OrderStatusEnum::data()[$data['order_status']]['name'];
        }
        // 付款状态
        if ($data['pay_status'] == PayStatusEnum::PENDING) {
            return '待支付';
        }
        if ($data['receipt_status'] == 10) {
            return '待完成';
        }
        // 待完成
        if ($data['order_status'] == 20) {
            return '已完成';
        }
        return $value;
    }
    /**
     * 获取器：订单状态文字描述
     * @param $value
     * @param $data
     * @return string
     */
    public function getStateTextAttr($value, $data): string
    {
        $value = (string) $data['order_status'];
        // 订单状态
        if ($data['order_status'] != OrderStatusEnum::NORMAL) {
            return OrderStatusEnum::data()[$data['order_status']]['name'];
        }
        // 付款状态
        if ($data['pay_status'] == PayStatusEnum::PENDING) {
            return '待支付';
        }
        // 发货状态
        if ($data['delivery_status'] != DeliveryStatusEnum::DELIVERED) {
            $enum = [DeliveryStatusEnum::NOT_DELIVERED => '待发货', DeliveryStatusEnum::PART_DELIVERED => '部分发货'];
            return $enum[$data['delivery_status']];
        }
        // 收货状态
        if ($data['receipt_status'] == ReceiptStatusEnum::NOT_RECEIVED) {
            return '待收货';
        }
        return $value;
    }
    public function getStatusTextAttr($value, $data): string
    {
        $value = '';
        // 订单状态
        if ($data['order_status'] != OrderStatusEnum::NORMAL) {
            return OrderStatusEnum::data()[$data['order_status']]['name'];
        }
        if ($data['service_status'] == ServiceStatusEnum::NOT_DELIVERED) {
            return '待接单';
        }

        // 付款状态
        if ($data['pay_status'] == PayStatusEnum::PENDING) {
            return '待支付';
        }
        if ($data['service_status'] != ServiceStatusEnum::NOT_DELIVERED) {
            $enum = [ServiceStatusEnum::DELIVERED => '待完成', ServiceStatusEnum::PART_DELIVERED => '待完成'];

            return $enum[$data['service_status']];
        }

        return $value;
    }
    /**
     * 获取器：订单金额(含优惠折扣)
     * @param $value
     * @param $data
     * @return string
     */
    public function getOrderPriceAttr($value, $data): string
    {
        // 兼容旧数据：订单金额
        if ($value == 0) {
            return helper::bcadd(helper::bcsub($data['total_price'], $data['coupon_money']), $data['update_price']);
        }
        return $value;
    }

    /**
     * 获取器：改价金额（差价）
     * @param $value
     * @return array
     */
    public function getUpdatePriceAttr($value): array
    {
        return [
            'symbol' => $value < 0 ? '-' : '+',
            'value'  => sprintf('%.2f', abs((float) $value)),
        ];
    }

    /**
     * 获取器：付款时间
     * @param $value
     * @return false|string
     */
    public function getPayTimeAttr($value)
    {
        return format_time($value);
    }

    /**
     * 获取器：发货时间
     * @param $value
     * @return false|string
     */

    public function getDeliveryTimeAttr($value): string
    {

        return Date('Y-m-d H:i', $value);
    }

    /**
     * 获取器：收货时间
     * @param $value
     * @return false|string
     */
    public function getReceiptTimeAttr($value)
    {
        return format_time($value);
    }

    /**
     * 获取器：来源记录的参数
     * @param $json
     * @return array
     */
    public function getOrderSourceDataAttr($json): array
    {
        return $json ? helper::jsonDecode($json) : [];
    }

    public function parkImage1(): HasOne
    {
        return $this->hasOne('UploadFile', 'file_id', 'park_file1')
            ->bind(['image_url' => 'preview_url']);
    }

    public function parkImage2(): HasOne
    {
        return $this->hasOne('UploadFile', 'file_id', 'park_file2')
            ->bind(['image_url2' => 'preview_url']);
    }
    /**
     * 修改器：来源记录的参数
     * @param array $data
     * @return string
     */
    public function setOrderSourceDataAttr(array $data): string
    {
        return helper::jsonEncode($data);
    }

    /**
     * 生成订单号
     * @return string
     */
    public function orderNo(): string
    {
        return OrderService::createOrderNo();
    }

    /**
     * 订单详情
     * @param $where
     * @param array $with
     * @return static|array|null
     */
    public static function detail($where, array $with = [])
    {
        is_array($where) ? $filter = $where : $filter['order_id'] = (int) $where;
        return self::get($filter, $with);
    }

    /**
     * 批量获取订单列表
     * @param $orderIds
     * @param array $with
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListByIds(array $orderIds, array $with = [])
    {
        $data = $this->getListByInArray('order_id', $orderIds, $with);
        return helper::arrayColumn2Key($data, 'order_id');
    }

    /**
     * 批量获取订单列表
     * @param $field
     * @param $data
     * @param array $with
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getListByInArray($field, $data, array $with = []): \think\Collection
    {
        return $this->with($with)
            ->where($field, 'in', $data)
            ->where('is_delete', '=', 0)
            ->select();
    }

    /**
     * 根据订单号批量查询
     * @param $orderNos
     * @param array $with
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListByOrderNos($orderNos, array $with = []): \think\Collection
    {
        return $this->getListByInArray('order_no', $orderNos, $with);
    }

    /**
     * 批量更新订单
     * @param $orderIds
     * @param $data
     * @return bool|false
     */
    public function onBatchUpdate($orderIds, $data): bool
    {
        return static::updateBase($data, [['order_id', 'in', $orderIds]]);
    }

    /**
     * 派单-陪诊
     * @param int $clerkId 门店店员ID
     * @param bool $syncMpWeixinShipping 同步至微信小程序
     * @return bool|false|int
     */
    public function confirmPaidanRunner(int $runnerId, bool $syncMpWeixinShipping = false)
    {
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS

            || in_array($this['order_status'], [OrderStatusEnum::CANCELLED, OrderStatusEnum::APPLY_CANCEL])
        ) {
            $this->error = '该订单不满足派单条件';
            return false;
        }

        return $this->transaction(function () use ($runnerId, $syncMpWeixinShipping) {

            if ($this['runner_id'] > 0) {
                //从新派单
                Db::name('store_shop_runner')->where('runner_id', $this['runner_id'])->update(['work_status' => 10]);

            }
            // 更新订单状态：已发货、已收货
            $status = $this->save([
                'runner_id'      => $runnerId, // 核销员
                'service_status' => 10,
                'paidan_time'    => time(),
            ]);

            //工作中
            Db::name('store_shop_runner')->where('runner_id', $runnerId)->update(['work_status' => 20]);

            $userId    = Db::name('store_shop_runner')->where('runner_id', $runnerId)->value('user_id');
            $shop_name = Db::name('store_shop')->where('shop_id', $this['extract_shop_id'])->value('shop_name');

            $manage_uni = Db::name('user')->alias('u')
                ->join('user_oauth o', 'o.user_id=u.user_id')
                ->where('o.is_delete', 0)
                ->where('u.user_id', $userId)
                ->value('o.unionid');
            if ($manage_uni) {
                $user_manage = Db::name('user_oauth_wxapp')
                    ->where('unionid', $manage_uni)
                    ->value('open_id');
                if ($user_manage) {
                    $open_id = $user_manage;
                    //发送公众号信息
                    $MessageService         = new MessageService;
                    $content['template_id'] = 'NOoNoJK9J1xO2T6-e1-JN1cYgoZZImyoPO3gIyXswto';
                    $content['page']        = 'pagesNew/order/runner/detail?orderId=' . $this['order_id'];

                    $content['data']['thing5'] = $shop_name;

                    $content['data']['thing1'] = $this['goods'][0]['goods_name'];
                    $content['data']['const6'] = '已支付成功';

                    $content['data']['thing2']        = $this['real_name'];
                    $content['data']['phone_number3'] = $this['mobile'];

                    $MessageService->send($open_id, $content);

                }
            }

            return $status;
        });
    }

    /**
     * 派单-泊车
     * @param int $clerkId 门店店员ID
     * @param bool $syncMpWeixinShipping 同步至微信小程序
     * @return bool|false|int
     */
    public function confirmPaidanPark(int $driverId, bool $syncMpWeixinShipping = false)
    {
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS

            || in_array($this['order_status'], [OrderStatusEnum::CANCELLED, OrderStatusEnum::APPLY_CANCEL])
        ) {
            $this->error = '该订单不满足派单条件';
            return false;
        }

        return $this->transaction(function () use ($driverId, $syncMpWeixinShipping) {

            if ($this['driver_id'] > 0) {
                //从新派单
                Db::name('store_shop_driver')->where('driver_id', $this['driver_id'])->update(['work_status' => 10]);

            }
            // 更新订单状态：已发货、已收货
            $status = $this->save([
                'driver_id'      => $driverId, // 核销员
                'service_status' => 10,
                'paidan_time'    => time(),
            ]);

            //工作中
            Db::name('store_shop_driver')->where('driver_id', $driverId)->update(['work_status' => 20]);

            $userId = Db::name('store_shop_driver')->where('driver_id', $driverId)->value('user_id');

            $manage_uni = Db::name('user')->alias('u')
                ->join('user_oauth o', 'o.user_id=u.user_id')
                ->where('o.is_delete', 0)
                ->where('u.user_id', $userId)
                ->value('o.unionid');
            if ($manage_uni) {
                $user_manage = Db::name('user_oauth_wxapp')
                    ->where('unionid', $manage_uni)
                    ->value('open_id');
                if ($user_manage) {
                    $open_id = $user_manage;
                    if ($this['service_type'] == 20) {
                        //发送公众号信息
                        $MessageService         = new MessageService;
                        $content['template_id'] = 'LGSP4shUgG__86mPAXgzdNBQE8AzfUzhGAq0Y0vdqaM';
                        $content['page']        = 'pagesNew/order/park/index';

                        $content['data']['thing3']        = $this['real_name'];
                        $content['data']['phone_number4'] = $this['mobile'];
                        $content['data']['thing5']        = $this['address'];
                        $content['data']['thing14']       = '上门接送车服务';
                    } else {
                        //发送公众号信息
                        $MessageService         = new MessageService;
                        $content['template_id'] = 'htPaYoSKTiJzlcXJmmLNX_gVLRAudmwVSgV028RAED8';
                        $content['page']        = 'pagesNew/order/park/index';

                        $content['data']['car_number1'] = $this['car_no'];
                        $content['data']['time4']       = $this['peihu_time'];
                        $content['data']['thing20']     = $this['real_name'];
                    }

                    $MessageService->send($open_id, $content);

                }
            }

            return $status;
        });
    }
    /**
     * 派单-其他服务
     * @param int $clerkId 门店店员ID
     * @param bool $syncMpWeixinShipping 同步至微信小程序
     * @return bool|false|int
     */
    public function confirmPaidan(int $clerkId, $data)
    {
        if($this['is_xufei']==1){

        }else{
            if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || in_array($this['order_status'], [OrderStatusEnum::CANCELLED, OrderStatusEnum::APPLY_CANCEL])
        ) {
            $this->error = '该订单不满足派单条件';
            return false;
        }
        }
        

        return $this->transaction(function () use ($clerkId, $data) {
            if ($this['hour_type'] == 20) {
                //24小时
                $hour_price = round($data['day_price'] / 48, 4);
            } else {
                $hour_price = round($data['day_price'] / 24, 4);
            }
            // 更新订单状态：已发货、已收货
            $status = $this->save([
                'extract_clerk_id' => $clerkId,           // 核销员
                'day_price'        => $data['day_price'], //日薪
                'hour_price'       => $hour_price,
                'group_id'         => $data['groupId'],
                'service_status'   => 10,
                'paidan_time'      => time(),
            ]);

            $dd = [];
            if ($data['is_group'] == 20) {
                //非班组
                $order['order_id']    = $this['order_id'];
                $order['money']       = $data['day_price'];
                $order['hour_price']  = $hour_price;
                $order['clerk_id']    = $clerkId;
                $order['store_id']    = $this['store_id'];
                $order['create_time'] = time();
                $dd[]                 = $order;

                //陪护中
                Db::name('store_shop_clerk')->where('clerk_id', $clerkId)->update(['work_status' => 20]);
            } else {
                $clerkIds = Db::name('store_shop_clerk_group')->where('id', $data['groupId'])->value('clerk_ids');
                $clerkIds = json_decode($clerkIds);
                //班组
                Db::name('store_shop_clerk')->where('clerk_id', 'in', $clerkIds)->update(['work_status' => 20]);

                foreach ($clerkIds as $key => $clerk_id) {
                    $order['order_id']    = $this['order_id'];
                    $order['money']       = $data['day_price'];
                    $order['hour_price']  = $hour_price;
                    $order['clerk_id']    = $clerk_id;
                    $order['store_id']    = $this['store_id'];
                    $order['create_time'] = time();
                    $dd[]                 = $order;
                }

            }

            //护理员记录
            Db::name('order_clerk')->insertAll($dd);

            return $status;
        });
    }

    /**
     * 派单-其他服务
     * @param int $clerkId 门店店员ID
     * @param bool $syncMpWeixinShipping 同步至微信小程序
     * @return bool|false|int
     */
    public function confirmPaidanChange(int $clerkId, $data)
    {
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || in_array($this['order_status'], [OrderStatusEnum::CANCELLED, OrderStatusEnum::APPLY_CANCEL])
        ) {
            $this->error = '该订单不满足派单条件';
            return false;
        }

        $out_price = 0;
        $out_hour  = 0;

        $total_price = $data['real_day'] * $this['goods'][0]['goods_price'];

        $total_price += (int) $data['real_hour'] * $this['hour_price'] * 2;

        $out_price = (int) $data['out_hour'] * $this['hour_price'] * 2;

        $total_price += $out_price;

        $out_hour = $data['out_hour'];
        $shengyu  = $this['total_price'] - $this['bed_fee'] - $this['money_total'];

        if ($total_price > $shengyu) {

            $this->error = '工资，超过可结算金额';
        }

        if ($this['extract_clerk_id'] > 0) {
            //从新派单
            Db::name('store_shop_clerk')->where('clerk_id', $this['extract_clerk_id'])->update(['work_status' => 10]);

        }
        //结算原陪护师
        // 工资明细
        $capital['money']       = $total_price;
        $capital['store_id']    = $this['store_id'];
        $capital['order_id']    = $this['order_id'];
        $capital['clerk_id']    = $this['extract_clerk_id'];
        $capital['out_hour']    = $data['out_hour'];
        $capital['real_day']    = $data['real_day'];
        $capital['real_hour']   = $data['real_hour'];
        $capital['create_time'] = time();
        $capital['flow_type']   = 10;
        $capital['describe']    = '陪护工资：' . $this['order_no'];
        Db::name('store_shop_clerk_capital')->insert($capital);

        $money_total = $this['money_total'] + $total_price;

        return $this->transaction(function () use ($clerkId, $data, $money_total) {

            if ($this['hour_type'] == 20) {
                //24小时
                $hour_price = round($data['day_price'] / 48, 4);
            } else {
                $hour_price = round($data['day_price'] / 24, 4);
            }

            // 更新订单状态：已发货、已收货
            $status = $this->save([
                'extract_clerk_id' => $clerkId, // 核销员
                'day_price'        => $data['day_price'],
                'real_day'         => $data['real_day'] + $this['real_day'],
                'real_hour'        => $data['real_hour'] + $this['real_hour'],
                'out_hour'         => $data['out_hour'] + $this['out_hour'],
                'hour_price'       => $hour_price,
                'money_total'      => $money_total,
                'service_status'   => 10,
                'paidan_time'      => time(),
            ]);
            //陪护中
            Db::name('store_shop_clerk')->where('clerk_id', $clerkId)->update(['work_status' => 20]);

            return $status;
        });
    }
    /**
     * 确认核销（自提订单）
     * @param int $clerkId 门店店员ID
     * @param bool $syncMpWeixinShipping 同步至微信小程序
     * @return bool|false|int
     */
    public function confirmExtract(int $clerkId, bool $syncMpWeixinShipping = false)
    {
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || $this['delivery_type'] != DeliveryTypeEnum::EXTRACT
            || $this['delivery_status'] == DeliveryStatusEnum::DELIVERED
            || in_array($this['order_status'], [OrderStatusEnum::CANCELLED, OrderStatusEnum::APPLY_CANCEL])
        ) {
            $this->error = '该订单不满足核销条件';
            return false;
        }
        // 验证订单是否满足发货条件
        if (! $this->verifyDeliveryForExtract($this)) {
            return false;
        }
        return $this->transaction(function () use ($clerkId, $syncMpWeixinShipping) {
            // 更新订单状态：已发货、已收货
            $status = $this->save([
                'extract_clerk_id' => $clerkId, // 核销员
                'delivery_status'  => DeliveryStatusEnum::DELIVERED,
                'delivery_time'    => time(),
                'receipt_status'   => ReceiptStatusEnum::RECEIVED,
                'receipt_time'     => time(),
                'order_status'     => OrderStatusEnum::COMPLETED,
            ]);
            // 新增订单核销记录
            ShopOrder::add($this['order_id'], $this['extract_shop_id'], $this['extract_clerk_id']);
            // 执行订单完成后的操作
            $OrderCompleteService = new OrderCompleteService();
            $OrderCompleteService->complete([$this], static::$storeId);
            // 发货信息同步微信平台
            (new ShippingService)->syncMpWeixinShipping($this, [
                // 同步至微信小程序《发货信息录入》
                'syncMpWeixinShipping' => (int) $syncMpWeixinShipping,
                // 物流模式：1物流配送 3虚拟商品 4用户自提
                'logisticsType'        => ShippingService::DELIVERY_EXTRACT,
            ]);
            return $status;
        });
    }

    /**
     * 验证订单是否满足发货条件
     * @param $order
     * @return bool
     */
    private function verifyDeliveryForExtract($order): bool
    {
        $orderSource = OrderSourceFactory::getFactory($order['order_source']);
        if (! $orderSource->checkOrderByDelivery($order)) {
            $this->error = $orderSource->getError();
            return false;
        }
        return true;
    }
    /**
     * 更新订单来源记录ID
     * @param int $orderId
     * @param int $soureId
     * @return bool
     */
    public static function updateOrderSourceId(int $orderId, int $soureId): bool
    {
        return static::updateOne(['order_source_id' => $soureId], $orderId);
    }

    /**
     * 记录是否已同步微信小程序发货信息管理
     * @param int $orderId
     * @param bool $status
     * @return bool
     */
    public static function updateSyncWeixinShipping(int $orderId, bool $status): bool
    {
        return static::updateOne(['sync_weixin_shipping' => (int) $status], $orderId);
    }
}
